<?php

namespace app\common\shop;

use think\Db;
use think\Model;
use think\model\concern\SoftDelete;

// 收货地址
class AddressModel extends model {
    use SoftDelete;//开启了软删除
    protected  $deleteTime = 'deltime';
    // 完整数据表名
    protected $table = 'shop_address';

    /**
     * [建表]
     * @return
     */
    public static function createTable(){
        return Db::query("Create Table If Not Exists `shop_address`(
             `id` int(11) NOT NULL AUTO_INCREMENT,
             `uid` int(11) NOT NULL COMMENT '会员id',
             `name` varchar(255) NOT NULL COMMENT '收货人',
             `mobile` varchar(255) NOT NULL COMMENT '手机号',
             `province` varchar(255) NOT NULL COMMENT '省',
             `city` varchar(255) NOT NULL COMMENT '市',
             `area` varchar(255) NOT NULL COMMENT '区',
             `address` varchar(255) NOT NULL COMMENT '详细地址',
             `createtime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '时间',
             `deltime` int(11) DEFAULT NULL COMMENT '删除时间',
             `isdefault` int(11) NOT NULL DEFAULT '0' COMMENT '默认 1默认',
             `updatetime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
             PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='收货地址'");
    }

    /**
     * [添加]
     * @return
     */
    public static function add($data){
        $data['createtime'] = time();
        $data['updatetime'] = time();
        if(isset($data['isdefault']) && $data['isdefault'] == 1){
            self::where('isdefault',1)->where('uid',$data['uid'])->setField('isdefault',0);
        }
        return self::insertGetId($data);
    }

    /**
     *
     * [修改]
     * @return
     */
    public static function edit($data,$id){
        $data['updatetime'] = time();
        if(isset($data['isdefault']) && $data['isdefault'] == 1){
            $uid = self::where('id',$id)->value('uid');
            self::where('isdefault',1)->where('uid',$uid)->setField('isdefault',0);
            $data['isdefault'] = 1;
        }
        return self::where('id',$id)->update($data);
    }

    /**
     * [获取默认地址]
     * @return
     */
    public static function getDefault($uid){
        return self::where('uid',$uid)->where('isdefault',1)->find();
    }

    /**
     * [设置默认地址]
     * @return
     */
    public static function setDefault($id,$isdefault=1){
        if($isdefault ==1){
            $uid = self::where('id',$id)->value('uid');
            self::where('isdefault',1)->where('uid',$uid)->setField('isdefault',0);
        }
        return self::where('id',$id)->setField('isdefault',$isdefault);
    }
    /**
     * [获取单条信息]
     * @return
     */
    public static function getInfo($id,$uid){
        return self::where('id',$id)->where('uid',$uid)->find();
    }
}